package chris.routing;

import chris.ConFactory;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeoutException;

/**
 * EmitLog
 *
 * @author nanxin.chen
 * @since 2017/7/5
 */
public class ReceiveLogsDirect {

    public static final String       EXCHANGE_NAME = "direct_logs";
    public static final List<String> ROUTING_KEYS  = Arrays.asList("info", "warning", "error");


    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory cf = ConFactory.getConnectionFactory();
        Connection con = cf.newConnection();
        Channel channel = con.createChannel();

        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
        String queueName = channel.queueDeclare().getQueue();
        String routingKey = ROUTING_KEYS.get(2);
        channel.queueBind(queueName, EXCHANGE_NAME, routingKey);
        System.out.println("routing key : " + routingKey);

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
            }
        };

        channel.basicConsume(queueName, true, consumer);
    }

}
